package com.central.apps.service.impl;

import com.central.app.dao.CommonDao;
import com.central.app.service.HandlerService;
import com.central.apps.service.BudgetService;
import com.central.apps.service.ProjectCostStatisticService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目管理成本汇总接口实现类
 *
 * @author 李大超
 * @date 2023/1/30
 */
@Slf4j
@Service
public class ProjectCostStatisticServiceImpl implements ProjectCostStatisticService {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private BudgetService budgetService;

    /**
     * 项目成本汇总
     *
     * @param proId
     * @param costItemId
     * @param actualAmt
     */
    @Override
    public void costStatistic(Integer proId, Integer costItemId, BigDecimal actualAmt) throws Exception {
        if (actualAmt == null || actualAmt.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }

        // 更新年度预算预算项明细信息
        List<Map<String, Object>> list = handlerService.findBySql("select pbiid, pbiparentid from gq_procoststructure where status = '可用' and id in (select pcsid from gq_procostelements where status = '可用' and id = " + costItemId + ")");
        if (CollectionUtils.isNotEmpty(list)){
            Map<String, Object> map = list.get(0);
            // 预算项id
            Integer pbiId = MapUtils.getInteger(map, "pbiid");

            // 更新年度预算预算项明细信息
            budgetService.updateBudgetInfo(proId, pbiId, actualAmt);
        }
    }

    /**
     * 成本占用或者释放
     *
     * @param proId
     * @param costItemId
     * @param applyAmt
     * @param flag: true-占用, false-释放
     */
    @Override
    public void costOccupyRelease(Integer proId, Integer costItemId, BigDecimal applyAmt, boolean flag) throws Exception {
        // 更新年度预算预算项明细信息
        List<Map<String, Object>> list = handlerService.findBySql("select pbiid from gq_procoststructure where status = '可用' and id in (select pcsid from gq_procostelements where status = '可用' and id = " + costItemId + ")");
        if (CollectionUtils.isNotEmpty(list)){
            Map<String, Object> map = list.get(0);
            // 预算项id
            Integer pbiId = MapUtils.getInteger(map, "pbiid");

            // 更新年度预算预算项占用/释放相关信息
            budgetService.budgetOccupyRelease(proId, pbiId, applyAmt, flag);
        }
    }
}
